package atm.routing;

import java.util.ArrayList;

import atm.Recharge;
import atm.connection.Connect;

/**
*
* @author Pablo
*/

public class RoutePlanner {
	
	ArrayList<AtmData> atms;
	
	public RoutePlanner() {
		
		
	}
	
	//ta metoda zwraca listę id bankomatów uporządkowaną wg kolejności uzupełniania podczas jednego wyjazdu kuriera
	public ArrayList<Integer> getSchedule(ArrayList<Recharge> atmsToRecharge) {
		
		int[] atmsId = new int[atmsToRecharge.size()];
		
		for(int i=0;i<atmsToRecharge.size();i++) {
			atmsId[i] = atmsToRecharge.get(i).getId_bankomat();
		}
		atms = getAtmsFromDatabase(atmsId);
		
		ArrayList<Integer> schedule = new ArrayList<Integer>();
		int visited = 0;
		int atmCount = atms.size();
		AtmData currentAtm = findFirstAtm(atms);
		
		while(visited < atmCount) {
			
			schedule.add(currentAtm.getId());
			currentAtm.setVisited(true);
			visited++;	
			currentAtm = findClosestAtm(currentAtm,atms);
						
		}
		return schedule;
	}
	
	public AtmData findFirstAtm(ArrayList<AtmData> atms) {
		
		double min = 1000;
		AtmData atm = null;
		
		for(AtmData a:atms) {
			if(a.getLatitude()< min) {
				min = a.getLatitude();
				atm = a;
			}
		}
		return atm;
	}
	
	public AtmData findClosestAtm(AtmData currentAtm, ArrayList<AtmData> atms) {
		
		double distance = 100;
		double longitude = currentAtm.getLongitude();
		double latitude = currentAtm.getLatitude();
		AtmData closestAtm = null;
		
		for(AtmData a:atms) {
			if(a.getId()!=currentAtm.getId() && !a.isVisited()) {
				double tmpDistance = Math.sqrt(Math.pow((longitude-a.getLongitude()), 2)+Math.pow(latitude-a.getLatitude(), 2));
				if(tmpDistance < distance) {
					distance = tmpDistance;
					closestAtm = a;		
				}
			}
		}
		return closestAtm;
	}
	
	private ArrayList<AtmData> getAtmsFromDatabase(int[] atmIds) {
		
		Connect conn = new Connect();
		conn.getConnected();
		return conn.getChosenAtms(atmIds);
		
	}
}

